package com.GetIp;
    import java.io.*;
import java.net.*;

    public class Main96{
        public static void main(String[] args) {
            int port = 12345; // 定义服务器端口
            try (ServerSocket serverSocket = new ServerSocket(port)) {
                System.out.println("服务器已启动，等待客户端连接...");

                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("客户端已连接: " + clientSocket.getInetAddress().getHostAddress());
                    ClientHandler clientHandler = new ClientHandler(clientSocket);
                    new Thread(clientHandler).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    class ClientHandler implements Runnable {
        private Socket clientSocket;
        public ClientHandler(Socket socket) {
            this.clientSocket = socket;
        }
        @Override
        public void run() {
            try (
                    InputStream input = clientSocket.getInputStream();
                    OutputStream output = clientSocket.getOutputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    PrintWriter writer = new PrintWriter(output, true)
            ) {
                String clientMessage;
                while ((clientMessage = reader.readLine()) != null) {
                    System.out.println("收到客户端消息: " + clientMessage);
                    writer.println("服务器回应: " + clientMessage);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
